package com.example.filter;

import com.example.utils.JwtTokenProvider;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.beans.factory.ObjectProvider;

import java.io.IOException;

/**
 * JWT身份验证过滤器，用于处理JWT令牌并设置身份验证信息
 * 继承OncePerRequestFilter以确保每次请求只执行一次过滤
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // JWT令牌提供者，用于处理JWT令牌的生成、解析和验证
    private final JwtTokenProvider tokenProvider;
    // 用户详细信息提供者，用于根据用户名获取用户详细信息
    // 使用ObjectProvider以支持延迟获取UserDetailsService实例
    private final ObjectProvider<UserDetailsService> userDetailsService;

    /**
     * 执行实际的过滤逻辑
     * 从HTTP请求中获取JWT令牌，验证令牌有效性，设置身份验证信息
     *
     * @param request     HTTP请求
     * @param response    HTTP响应
     * @param filterChain 过滤链，用于将请求传递给下一个过滤器或目标
     * @throws ServletException 如果过滤过程中发生Servlet异常
     * @throws IOException      如果过滤过程中发生I/O异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        String token = getJwtFromRequest(request);

        if (StringUtils.hasText(token)) {
            try {
                if (tokenProvider.validateToken(token)) {
                    String username = tokenProvider.getUsernameFromToken(token);
                    UserDetails userDetails = userDetailsService.getIfAvailable()
                            .loadUserByUsername(username);

                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());

                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (Exception ex) {
                // 捕获 JWT 验证过程中的异常，如 SignatureException、MalformedJwtException、ExpiredJwtException 等
                logger.warn("JWT validation failed: " + ex.getMessage());
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的 Token");
                return; // 终止请求，不再继续执行过滤链
            }
        }

        filterChain.doFilter(request, response);
    }


    /**
     * 从HTTP请求中提取JWT令牌
     * 仅处理"Authorization"头以"Bearer "开头的情况
     *
     * @param request HTTP请求
     * @return 提取的JWT令牌，如果没有找到或格式不正确则返回null
     */
    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
